#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>

#include "video.h"

char g_server_addr[16];
volatile int g_server_port;

volatile int g_client_num = 0;

void net_slaver_thread(void) {

    struct sockaddr_in server_addr;
    int sockfd;
    int nbytes;
    char recv_buf[16];
    int ret;
    int frame_num;

    if (inet_aton(g_server_addr, &server_addr.sin_addr) == 0) {
        fprintf(stderr, "the hostip is not right!");
        return;
    }

    // create socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        fprintf(stderr, "Socket Error:%s\n\a", strerror(errno));
        return;
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(g_server_port);

    printf("Connecting to %s:%d\n", g_server_addr, g_server_port);
    if (connect(sockfd, (struct sockaddr *) &server_addr,
            sizeof(struct sockaddr)) == -1) {
        fprintf(stderr, "Connect Error:%s\n\a", strerror(errno));
        return;
    }

    recv_buf[8] = '\0';
    // connected
    while (1) {
        if ((nbytes = read(sockfd, recv_buf, 8)) == -1) {
            fprintf(stderr, "Read Error:%s\n", strerror(errno));
            goto NET_THREAD_END;
        }
        if (strcmp(recv_buf, "VIDEOEND") == 0) {
            goto NET_THREAD_END;
        } else {
            frame_num = atoi(recv_buf);
            if (g_frame_num < frame_num) {
                g_frame_num++;
                ret = video_play_frame();
                if (ret != 0) {
                    fprintf(stderr, "video_play_frame errors\n");
                    goto NET_THREAD_END;
                } else {
                    //fprintf(stderr, "vframe: %d\n", g_frame_num);
                }
            }
        }
    }

NET_THREAD_END:
    close(sockfd);
    fprintf(stderr, "slaver socket has been closed\n");

}

static void net_master_client_thread(void *arg) {
    int frame_num = 0;
    int ret;
    int client_sock_fd = (int) arg;
    char send_buf[16];

    while (1) {
        if (frame_num < g_frame_num) {
            frame_num++;
            sprintf(send_buf, "%08d", frame_num);
            ret = write(client_sock_fd, send_buf, 8);
            //printf("Client_%d: %d\n", client_sock_fd, frame_num);
            if (ret == -1) {
                fprintf(stderr, "Write error:%s\n", strerror(errno));
                break;
            }
        }

        if (g_frame_num == -1) {
            ret = write(client_sock_fd, "VIDEOEND", 8);
            if (ret == -1) {
                fprintf(stderr, "Write error:%s\n", strerror(errno));
            }
            break;
        }
    }

    close(client_sock_fd);
    fprintf(stderr, "client socket has been closed\n");
}

void net_master_thread(void) {
    int sockfd, client_sock_fd;
    struct sockaddr_in server_addr;
    struct sockaddr_in client_addr;
    int sin_size;
    pthread_t client_thread_id;
    int ret;
    int on;

    // create socket
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
        fprintf(stderr, "Socket error:%s\n\a", strerror(errno));
        return;
    }

    // Enable address reuse, otherwise the binding address will go into TIME_WAIT states for several minutes
    on = 1;
    ret = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));

    // fill the struct of IP address
    bzero(&server_addr, sizeof(struct sockaddr_in));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    server_addr.sin_port = htons(g_server_port);

    // bind
    printf("Binding on port: %d\n", g_server_port);
    if (bind(sockfd, (struct sockaddr *) &server_addr, sizeof(struct sockaddr))
            == -1) {
        fprintf(stderr, "Bind error:%s\n\a", strerror(errno));
        return;
    }

    if (listen(sockfd, 5) == -1) {
        fprintf(stderr, "Listen error:%s\n\a", strerror(errno));
        return;
    }

    while (1) {
        sin_size = sizeof(struct sockaddr_in);
        if ((client_sock_fd = accept(sockfd, (struct sockaddr *) &client_addr,
                (socklen_t *) &sin_size)) == -1) {
            fprintf(stderr, "Accept error:%s\n\a", strerror(errno));
            exit(1);
        }
        ret = pthread_create(&client_thread_id, NULL,
                (void *) net_master_client_thread, (void *) client_sock_fd);
        if (ret != 0) {
            fprintf(stderr, "Create client thread error!\n");
        }
        g_client_num++;
        fprintf(stderr, "Server get connection from %s, %d\n",
                inet_ntoa(client_addr.sin_addr), g_client_num);
        if (g_client_num >= 2) {
            break;
        }
    }
    close(sockfd);

    fprintf(stderr, "listening socket has been closed\n");
}
